package com.yxjx.duoxue.comment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.activities.ActivityIntroductionActivity;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.customview.YxGridView;
import com.yxjx.duoxue.customview.YxImageView;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.images.CommentBitmaps;
import com.yxjx.duoxue.images.FileUtils;
import com.yxjx.duoxue.images.PhotoActivity;
import com.yxjx.duoxue.images.PublishedActivity;
import com.yxjx.duoxue.images.TestPicActivity;
import com.yxjx.duoxue.images.PublishedActivity.GridAdapter;
import com.yxjx.duoxue.images.PublishedActivity.PopupWindows;
import com.yxjx.duoxue.images.PublishedActivity.GridAdapter.ViewHolder;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

public class AddingCommentsActivity extends BaseActionBarActivity {
	
	public static final int REQ_CODE_TAKE_PICTURE = 0;
	public static final int REQ_CODE_SELECT_IMGS = 1;
	public static final int REQ_CODE_LOGIN_FOR_ADD_COMMENT = 2;
	
	// 添加评论相关的事件。
	public static final int MSG_UPLOAD_SINGLE_FILE_DONE = 1;
	public static final int MSG_UPLOAD_ALL_FILES_DONE = 2;
	public static final int MSG_ADD_COMMENT_DONE = 3;
	public static final int MSG_LOADING_SUBMIT_IMAEGS = 4;
	
	private GridView mNoScrollgridview;
	private GridAdapter mThumbnailsAdapter;
	private TextView mSubmit;
	private Context mContext;
	
	private int mCommentType = -1;
	private String mItemId = "";
	private boolean isSubmitingComment = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_adding_comments);
		customizeActionBarTitle("添加点评");
		mContext = this;
		
		// 清空图片列表
		CommentBitmaps.bitmapAddressArray.clear();
		CommentBitmaps.bitmapArray.clear();
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mCommentType = bundle.getInt(CommentFunctionView.KEY_COMMENT_TYPE);
			mItemId = bundle.getString(CommentFunctionView.KEY_ITEM_ID);
			if (mCommentType == Yx.TYPE_ITEM_COURSE) {
				UIHelper.setText(findViewById(R.id.rating_total), R.id.rating_total_label, "课程评价：");
			}
			
			if (mCommentType == Yx.TYPE_ITEM_COURSE) {
				StatHelper.addKVEvent(mContext, "event_comment_add_",
						StatHelper.KEY_COURSE, mItemId);
			} else if (mCommentType == Yx.TYPE_ITEM_SCHOOL) {
				StatHelper.addKVEvent(mContext, "event_comment_add_",
						StatHelper.KEY_SCHOOL, mItemId);
			}
		}
		Init();

	}
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOADING_SUBMIT_IMAEGS:
				mThumbnailsAdapter.notifyDataSetChanged();
				break;
			case MSG_ADD_COMMENT_DONE:
				// 清空图片列表，然后关闭当前页面
				CommentBitmaps.bitmapAddressArray.clear();
				CommentBitmaps.bitmapArray.clear();
				mThumbnailsAdapter.notifyDataSetChanged();
				finish();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	private TextView mTextReminderNum;
	private OnClickListener mSubmitClickListener;
	private ProgressDialog dialog;
	
	// TODO
	class ImagePickerAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 5;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_grid_image_picker, null);
			} else {
				ret = arg1;
			}
			return ret;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mThumbnailsAdapter.notifyDataSetChanged();
	}
	
	public void Init() {
		
		findViewById(R.id.root).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				hideIME(arg0);
			}
		});
		
		mNoScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		mNoScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mThumbnailsAdapter = new GridAdapter(this);
		mThumbnailsAdapter.update();
		mNoScrollgridview.setAdapter(mThumbnailsAdapter);
		mNoScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == CommentBitmaps.bitmapArray.size()) {
					UIHelper.hideIME(arg1);
					new PopupWindows(AddingCommentsActivity.this, mNoScrollgridview);
				} else {
					Intent intent = new Intent(AddingCommentsActivity.this,
							PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

		mSubmit = (TextView) findViewById(R.id.submit);
		// 隐藏IME
		UIHelper.hideIME(mSubmit);
		mSubmitClickListener = new OnClickListener() {

			public void onClick(View v) {
				List<String> list = new ArrayList<String>();				
				for (int i = 0; i < CommentBitmaps.bitmapAddressArray.size(); i++) {
					String Str = CommentBitmaps.bitmapAddressArray.get(i).substring( 
							CommentBitmaps.bitmapAddressArray.get(i).lastIndexOf("/") + 1,
							CommentBitmaps.bitmapAddressArray.get(i).lastIndexOf("."));
					list.add(FileUtils.SDPATH+Str+".JPEG");		
					Utils.logd("Str = " + Str);
					Utils.logd("str = " + list.get(i));
				}
				// 高清的压缩图片全部就在  list 路径里面了
				// 高清的压缩过的 bmp 对象  都在 Bimp.bmp里面
				// 完成上传服务器后 .........
				addAComment(list);
			}
		};
		mSubmit.setOnClickListener(mSubmitClickListener);
		
		mRatingTotal = (RatingBar) findViewById(R.id.rating_total).findViewById(R.id.rating);
		mRatingTeach = (RatingBar) findViewById(R.id.rating_teach).findViewById(R.id.rating);
		mRatingTeacher = (RatingBar) findViewById(R.id.rating_teacher).findViewById(R.id.rating);
		mRatingEnvironment = (RatingBar) findViewById(R.id.rating_environment).findViewById(R.id.rating);
		mRatingTravel = (RatingBar) findViewById(R.id.rating_travel).findViewById(R.id.rating);
		String[] labelStrings = new String[] {
				"教学质量：",
				"师资力量：",
				"校区环境：",
				"交通便利：",
		};
		int[] labelId = new int[] {
				R.id.rating_teach,
				R.id.rating_teacher,
				R.id.rating_environment,
				R.id.rating_travel
		};
		for (int i = 0; i < labelStrings.length; i++) {
			((TextView) findViewById(labelId[i]).findViewById(R.id.label)).setText(labelStrings[i]);
		}
		mCommentText = (EditText) findViewById(R.id.comment_text);
		mTextReminderNum = (TextView) findViewById(R.id.remind_text_num);
		mCommentText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				int length = arg0.toString().length();
				mTextReminderNum.setText("" + (5000 - length));
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				
			}
		});
	}
	
	/**
	 * @param files
	 * @return
	 */
	private ArrayList<String> uploadAllFiles(List<String> files) {
		ArrayList<String> uploadedUrls = new ArrayList<String>();
		if (files == null) {
			return null;
		}
		
		UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
		if (ulRsp == null) {
			return null;
		}
		
		for (String filePath : files) {
			
			String url = "";
			try {
				url = UserReg.uploadFile(ulRsp, filePath, AddingCommentsActivity.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			if (!UIHelper.isEmpty(url)) {
				uploadedUrls.add(url);
			} else {
				// donothing
			}
		}
		
		return uploadedUrls;
	}
	
	private void addAComment(final List<String> files) {
		
		if (!checkComment()) {
			return;
		}
		
		final UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
		if (ulRsp == null) {
			startActivityForResult(new Intent(AddingCommentsActivity.this,
					UserLoginActivity.class), REQ_CODE_LOGIN_FOR_ADD_COMMENT);
			return;
		}
		
		if (isSubmitingComment) {
			return;
		}
		isSubmitingComment = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<String> urls = uploadAllFiles(files);
				if (files != null && urls != null && files.size() == urls.size()) {
					for (String item : urls) {
						Utils.logd("url: " + item);
					}
				}
				
				ResponseObject code = new ResponseObject(-1, "");
				try {
					code = UserReg.submitComment(ulRsp, mCommentType, getSchoolParams(urls),
							AddingCommentsActivity.this);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (code.getCode() == MsgCode.SUCCESS) {
					// 标记为已经访问过课程或活动
					Utils.writeToSharePreference(AddingCommentsActivity.this, Yx.KEY_HAS_APPOINT_OR_BUY_OR_COMMENT, "1");
					
					UIHelper.showTips(mSubmit, "点评成功");
					mHandler.sendEmptyMessage(MSG_ADD_COMMENT_DONE);
				} else {
					UIHelper.showTips(mSubmit, "点评失败," + MsgCode.descFor(code));
				}
				if (dialog != null) {
					dialog.dismiss();
					dialog = null;
				}
				isSubmitingComment = false;
				FileUtils.deleteDir();
			}
		}).start();
		dialog = MyProgressDialog.show(this, "", "正在提交");
	}
	
	private boolean checkComment() {
		String commentText = mCommentText.getText().toString();
		if (mRatingTotal.getRating() < 1) {
			UIHelper.showTips(mSubmit, "请做出总体评价评分");
			return false;
		}
		if (commentText.length() < 10) {
			UIHelper.showTips(mSubmit, "评论文字不得少于10字");
			return false;
		}
		return true;
	}
	
	private JSONObject getSchoolParams(ArrayList<String> urls) {
		JSONObject ret = new JSONObject();
		try {
			ret.put("id", mItemId);
			ret.put("level", (int) mRatingTotal.getRating());
			ret.put("level1", (int) mRatingTeach.getRating());
			ret.put("level2", (int) mRatingTeacher.getRating());
			ret.put("level3", (int) mRatingEnvironment.getRating());
			ret.put("level4", (int) mRatingTravel.getRating());
			if (urls != null && urls.size() != 0) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < urls.size() - 1; i++) {
					sb.append(urls.get(i));
					sb.append(",");
				}
				sb.append(urls.get((urls.size() - 1)));
				ret.put("imgs", sb.toString());
			}
			ret.put("text", mCommentText.getText().toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ret;
		
	}
	
	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1; // 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (CommentBitmaps.bitmapArray.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			convertView.findViewById(R.id.default_img).setVisibility(View.INVISIBLE);
			convertView.findViewById(R.id.item_grida_image).setVisibility(View.VISIBLE);
			
			if (position == CommentBitmaps.bitmapArray.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				convertView.findViewById(R.id.default_img).setVisibility(View.VISIBLE);
				convertView.findViewById(R.id.item_grida_image).setVisibility(View.INVISIBLE);
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(CommentBitmaps.bitmapArray.get(position));
			}
			

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					if (CommentBitmaps.bitmapAddressArray == null || CommentBitmaps.bitmapAddressArray.size() == 0) {
						return;
					}
					while (true) {
						if (CommentBitmaps.currentIndex == CommentBitmaps.bitmapAddressArray.size()) {
							Message message = new Message();
							message.what = MSG_LOADING_SUBMIT_IMAEGS;
							mHandler.sendMessage(message);
							break;
						} else {
							try {
								String path = CommentBitmaps.bitmapAddressArray.get(CommentBitmaps.currentIndex);
								System.out.println(path);
								Bitmap bm = CommentBitmaps.revitionImageSize(path);
								if (bm != null) {
									CommentBitmaps.bitmapArray.add(bm);
									String newStr = path.substring(
											path.lastIndexOf("/") + 1,
											path.lastIndexOf("."));
									FileUtils.saveBitmap(bm, "" + newStr);
								}
								CommentBitmaps.currentIndex += 1;
								Message message = new Message();
								message.what = MSG_LOADING_SUBMIT_IMAEGS;
								mHandler.sendMessage(message);
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		mThumbnailsAdapter.update();
		super.onRestart();
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(AddingCommentsActivity.this,
							TestPicActivity.class);
					startActivityForResult(intent, REQ_CODE_SELECT_IMGS);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});
		}
	}

	private String path = "";
	private RatingBar mRatingTotal;
	private RatingBar mRatingTeach;
	private RatingBar mRatingTeacher;
	private RatingBar mRatingEnvironment;
	private RatingBar mRatingTravel;
	private EditText mCommentText;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		
		File dir = new File(Environment.getExternalStorageDirectory() + "/yxjx");
		if(!dir.exists()){
			dir.mkdir();
		}
		
		File file = new File(dir, String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// 拍照图片大小不超过1M
		openCameraIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024*1024);
		startActivityForResult(openCameraIntent, REQ_CODE_TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQ_CODE_TAKE_PICTURE:
				if (CommentBitmaps.bitmapAddressArray.size() < 9 && resultCode == Activity.RESULT_OK) {
					CommentBitmaps.bitmapAddressArray.add(path);
				}
				mThumbnailsAdapter.notifyDataSetChanged();
				break;
			case REQ_CODE_LOGIN_FOR_ADD_COMMENT:
				// 登录成功后重新提交点评。
				mSubmitClickListener.onClick(null);
				break;
			}
		}
	}

}
